package OperationSystem.day1210.TCP.V2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private static class ServiceMan extends Thread {
        private final Socket socket;

        ServiceMan(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                //获取输入流
                InputStream is = socket.getInputStream();
                //封装成Scanner
                Scanner scanner = new Scanner(is, "UTF-8");
                //使用\r\n进行分割的方式，读取请求

                //等着第一个Client发送请求
                String request = scanner.nextLine();//nextLine把\r\n已经去掉了
                System.out.println("收到请求:" + request);

                //业务处理
                String response = request;

                //发送响应，也需要使用\r\n跟在后面，进行分割
                OutputStream os = socket.getOutputStream();//得到输出流
                //封装成PrintWriter
                PrintWriter writer = new PrintWriter(
                        new OutputStreamWriter(os, "UTF-8")
                );
                //发送响应
                writer.println(response);//println会帮我们在后面加\r\n
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //开店
        ServerSocket serverSocket = new ServerSocket(9898);
        ExecutorService threadPool = Executors.newFixedThreadPool(20);
        //循环处理任务
        //主线程只负责接待客人——建立连接的过程
        while (true) {
            /*
            Socket socket = serverSocket.accept();
            //所有业务处理的过程，交给线程取处理
            new ServiceMan(socket).start();
            *///更好的做法，引进线程池

            //各个线程之间，没有数据共享（主线程和工作线程共享socket）
            //所以天生是线程安全的
            Socket socket = serverSocket.accept();
            threadPool.execute(new ServiceMan(socket));
        }
    }
}